﻿package  {
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import flash.events.MouseEvent;

	
	public class Main extends MovieClip 
	{
		private var _snakeSpeed:uint;//每秒移动分母
		private var _snakeDirection:String; //蛇头当前方向
		private var _tailDirection:String;//尾巴方向
		private var _allDirection:Array;
		private var _turnX:int;//传递身体最后位置
		private var _turnY:int;
		private var _snakeMove:uint;//每秒移动分子
		private var _second:uint;//帧数进度
		private var _horizontal:int;//横向移动
		private var _vertical:int;//纵向移动
		private var _snakeHeight:uint;//蛇头高度
		private var _headTurnDirection:Boolean;//是否头在转向

		
		//蛇的身体部件们
		public var head:Head;
		public var body:Body;
		public var tail:Tail;
		public var newBody:Body;
		//存放动态身体们
		private var _allBody:Array;
		//奖品
		public var gift:Gift;
		public var newGift:Gift;
		private var _giftHit:Boolean;
		private var _bodyGrow:Boolean;
		
		//墙
		private var _allWall:AllWall;
		
		//界面
		private var _startUI:StartUI;
		private var _endUI:EndUI;
		private var _scoreUI:ScoreUI;
		
		
		//当前分数
		private var _score:uint;
		
	
		public function Main() 
		{
			
			startUI();
			
		}
		
		//开始界面
		private function startUI():void
		{
			_startUI = new StartUI();
			stage.addChild(_startUI);
			_startUI.startButton.addEventListener(MouseEvent.CLICK,onStartMouse);
			stage.addEventListener(KeyboardEvent.KEY_DOWN,onStartKeyboard);
			
			stopButton.visible = false;
			continueButton.visible = false;
			wall.visible = false;
		}
		
		//开始游戏
		private function onStartMouse(event:MouseEvent):void
		{
			gameStart();
		}
		
		private function onStartKeyboard(event:KeyboardEvent):void
		{
			trace(event.keyCode);
			if(event.keyCode == Keyboard.ENTER)
			{
				gameStart();
			}
		}
		
		private function gameStart():void
		{
			//用removeChild会失去flash焦点，奇葩啊
			//stage.removeChild(_startUI);
			//隐藏开始界面上的元件
			_startUI.startButton.visible = false;
			_startUI.startTitle.visible = false;
			//去除开始按监听
			_startUI.startButton.removeEventListener(MouseEvent.CLICK,onStartMouse);
			stage.removeEventListener(KeyboardEvent.KEY_DOWN,onStartKeyboard);
			
			init();
		}
		
		//游戏本体初始化
		private function init():void
		{
			//蛇各个部位创建
			_snakeSpeed = 15;//越小越快
			_snakeMove = 1;
			_second = 0;
			_turnX = 0;
			_turnY = 0;
			_horizontal = 1;
			_vertical = 0;
			_snakeDirection = "right";  
			_snakeHeight = 30;

			head = new Head();
			head.x = 375;
			head.y = 315;
			parent.addChild(head);
			
			body = new Body();
			body.x = 345;
			body.y = 315;
			parent.addChild(body);
			
			tail = new Tail();
			tail.x = 315;
			tail.y = 315;
			parent.addChild(tail);
			
			_allDirection = new Array();
			_allBody = new Array();
			_allBody.unshift( body );
			_bodyGrow = false;

			//分数板
			_score = 0;
			_scoreUI = new ScoreUI();
			parent.addChild(_scoreUI);
			_scoreUI.scoreText.text = "Score:"+_score;
			
			//停止,继续按钮
			setChildIndex(stopButton, numChildren - 1);
			setChildIndex(continueButton, numChildren - 2);
			stopButton.visible = true;
				
			//已在舞台放了墙（与STOPBUTTON层的问题纠结啊）
			_allWall = wall;
			_allWall.visible = true;
			
			
			//奖品创建
			gift = new Gift();
			gift.x = 495;
			gift.y = 315;
			_giftHit = false;
			parent.addChild(gift);
			newGift = new Gift();
			
			
			_headTurnDirection = false;

			//增加监听
			stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
			stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
			stopButton.addEventListener(MouseEvent.CLICK,onStopButtonMouse);
			stage.addEventListener(KeyboardEvent.KEY_DOWN,onStopButtonKeyboard);
		}
		
		private function onStopButtonMouse(event:MouseEvent):void
		{
			stopGame();
		}
		private function onStopButtonKeyboard(event:KeyboardEvent):void
		{
			if( event.keyCode == Keyboard.SPACE)
			{
				stopGame();
			}
			
		}
		
		private function onContinueButtonMouse(event:MouseEvent):void
		{
			continueGame();
		}
		private function onContinueButtonKeyboard(event:KeyboardEvent):void
		{
			if( event.keyCode == Keyboard.SPACE)
			{
				continueGame();
			}
			
		}
		private function stopGame():void
		{
			
			stopButton.visible = false;
			continueButton.visible = true;
			gift.stop();
			
			stopButton.removeEventListener(MouseEvent.CLICK,onStopButtonMouse);
			continueButton.addEventListener(MouseEvent.CLICK,onContinueButtonMouse);
			
			stage.removeEventListener(KeyboardEvent.KEY_DOWN,onStopButtonKeyboard);
			stage.addEventListener(KeyboardEvent.KEY_DOWN,onContinueButtonKeyboard);
			
			stage.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
			stage.removeEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
			
				
		}
		private function continueGame():void
		{
			stopButton.visible = true;
			continueButton.visible = false;
			gift.play();
			
			//鼠标
			continueButton.removeEventListener(MouseEvent.CLICK,onContinueButtonMouse);
			stage.removeEventListener(KeyboardEvent.KEY_DOWN,onContinueButtonKeyboard);
			
			//键盘
			stopButton.addEventListener(MouseEvent.CLICK,onStopButtonMouse);
			stage.addEventListener(KeyboardEvent.KEY_DOWN,onStopButtonKeyboard);
			
			stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
			stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
		
		}
		
		private function onEnterFrame(event:Event):void
		{
			headInspect();
			secondMove();
		}
		
		
		//头部碰撞判断
		private function headInspect():void
		{
			//头部碰到奖品
			if(head.hitTestPoint(gift.x,gift.y,true))
			{
				trace("gift");
				trace(gift.x);
				trace(gift.y);
				trace("-------------------");
				addScore();
				parent.removeChild(gift);
				
				//重新随机新的奖品&检查新奖品是否碰到蛇或者墙
				do
				{
					randomXY();
					_giftHit = false;
					
					if( head.hitTestPoint(gift.x,gift.y,true))
					{
						_giftHit = true;
					}
					for( var c:int = 0;c < _allBody.length - 1; c++ )
					{
						if( gift.x == _allBody[c].x && gift.y == _allBody[c].y )
						{
							_giftHit = true;
							break;
						}
					}
					if( tail.hitTestPoint(gift.x,gift.y,true))
					{
						_giftHit = true;
					}
					if( _allWall.hitTestPoint(gift.x,gift.y,true))
					{
						_giftHit = true;
					}
					
					
				}
				while( _giftHit )
				
				parent.addChild(gift);
				//_snakeSpeed -= 5;
				addBody(); 
			}
			//头部碰到墙
			else if(_allWall.hitTestPoint(head.x,head.y,true))
			{
				trace("gameover touch wall");
				gameOver();
			}
			//头部碰到身体和尾巴
			else
			{
			for( var b:int = 0;b < _allBody.length - 1; b++ )
				{
					if( head.x == _allBody[b].x && head.y == _allBody[b].y )
					{
						trace("gameover touch body");
						gameOver();
					}
					
				}
			if( head.x == tail.x && head.y == tail.y )
					{
						trace("gameover touch tail");
						gameOver();
					}
			}
		}
		
		//分数更新
		private function addScore():void
		{
			_score += 10;
			trace(_score);
			_scoreUI.scoreText.text = "Score:"+_score;
		}
		
		//随机GIFT位置
		private function randomXY():void
		{
			gift.x = 30*(1+Math.round((Math.random()*28))) - 15;
			gift.y = 30*(1+Math.round((Math.random()*8))) - 15;
		}
		
		//增加新身体
		private function addBody():void
		{
			newBody = new Body();
			_allBody.unshift( newBody );
			_bodyGrow = true;
			secondMove();
			//给个舞台上看不到的位置暂时放新身体
			newBody.x = -30;
			newBody.y = -30;
			parent.addChild(newBody);
			_snakeSpeed = (_snakeSpeed - 5)*0.95+5;
		}
		
		//每秒移动
		private function secondMove():void
		{
			
			_second = Math.floor( _snakeMove / _snakeSpeed );
			
			if(_second != 0)
			{
				//移动,置回1
				_snakeMove = 1;
				headMove();
			}
			_snakeMove++;
			
		}
		
		
		
		//头部移动
		private function headMove():void
		{		
			if( !_headTurnDirection )
			{
				head.x += _second*_horizontal * 30;
				head.y += _second*_vertical * 30;
				bodyMove();
			}
			else
			{
				_allDirection.push( _snakeDirection );
				_headTurnDirection = false;
				
				if( _snakeDirection == "up" )
				{
					head.rotation = -90;
					head.y -= _snakeHeight;
					bodyMove();
					_horizontal = 0;
					_vertical = -1;
				
				}
				else if( _snakeDirection == "down" )
				{
					
					head.rotation = 90;
					head.y += _snakeHeight;
					bodyMove();
					_horizontal = 0;
					_vertical = 1;
				}
				else if( _snakeDirection == "left" )
				{

					head.rotation = -180;
					head.x -= _snakeHeight;
					bodyMove();				
					_horizontal = -1;
					_vertical = 0;
				
				}
				else if( _snakeDirection == "right" )
				{

					head.rotation = 0;
					head.x += _snakeHeight;
					bodyMove();
					_horizontal = 1;
					_vertical = 0;
				
				}
				stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
			}
			
		}
		
		
		//身体移动
		private function bodyMove():void
		{
			if( _second != 0)
			{
				//最后一节body位置存下来给tail
				_turnX = _allBody[0].x;
				_turnY = _allBody[0].y;
				
				//身体长度>=2开始循环移动身体
				if( _allBody.length >= 2)
				{
					for( var i:int = 0;i < _allBody.length - 1; i++ )
					{
						var j:int = i + 1;
						_allBody[i].x = _allBody[j].x;
						_allBody[i].y = _allBody[j].y;
					}
				}
				body.x += _snakeHeight * _horizontal;
				body.y += _snakeHeight * _vertical;
				
				tailMove();
			}
		}
		
		//尾巴移动
		private function tailMove():void
		{
		
			//判断身体离尾巴距离超过一个身体！说明要转向啦！
			if(Math.abs( tail.x - _allBody[0].x ) == 30 && Math.abs( tail.y - _allBody[0].y ) == 30 )
			{
				//取出蛇头转向记录集~
				_tailDirection = _allDirection.shift();
				trace(_tailDirection);
				if( _tailDirection == "up")
				{
					if( tail.x - _allBody[0].x < 0)
					{
						tail.rotation -= 90;
					}
					else
					{
						tail.rotation += 90;
						
					}
				}
				else if( _tailDirection == "down")
				{
					if( tail.x - _allBody[0].x < 0)
					{
						tail.rotation += 90;
					}
					else
					{
						tail.rotation -= 90;
						
					}
				}
				else if( _tailDirection == "left")
				{
					if( tail.y - _allBody[0].y < 0)
					{
						tail.rotation += 90;
					}
					else
					{
						tail.rotation -= 90;
						
					}
				}
				else if( _tailDirection == "right")
				{
					if( tail.y - _allBody[0].y < 0)
					{
						tail.rotation -= 90;
					}
					else
					{
						tail.rotation += 90;
						
					}
				}
				trace(tail.rotation);
				
				
			}
			
			if(_bodyGrow)
			{
				_bodyGrow = false;
			}
			else
			{
				tail.x = _turnX;
				tail.y = _turnY;	
			}
			
		}
		
		//游戏结束
		private function gameOver():void
		{
			stage.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
			stage.removeEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
			_endUI = new EndUI();
			stage.addChild(_endUI);
			_endUI.restartButton.addEventListener(MouseEvent.CLICK,onRestart);
		}
		
		//重新开始游戏
		private function onRestart(event:MouseEvent):void
		{
			_endUI.restartButton.visible = false;
			_endUI.gameoverTitle.visible = false;
			stopButton.visible = true;
			init();
		}
		
		//方向操作
		private function onKeyDown(event:KeyboardEvent):void
		{
			trace("---------------------------");
			trace(event.keyCode);
			trace("---------------------------");
			
			if(event.keyCode == Keyboard.UP)
			{
				if( _snakeDirection == "left" ||  _snakeDirection == "right")
				{
					_snakeDirection = "up";
					_headTurnDirection = true;
					stage.removeEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
				}
			}
			else if(event.keyCode == Keyboard.DOWN )
			{
				if( _snakeDirection == "left" || _snakeDirection == "right")
				{
					_snakeDirection = "down";
					_headTurnDirection = true;
					stage.removeEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
				}
				
			}
			else if(event.keyCode == Keyboard.LEFT)
			{
				if( _snakeDirection == "up" || _snakeDirection == "down")
				{
				
					_snakeDirection = "left";
					_headTurnDirection = true;
					stage.removeEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);

				}
			}
			else if(event.keyCode == Keyboard.RIGHT)
			{
				if( _snakeDirection == "up" ||_snakeDirection == "down" )
				{
					_snakeDirection = "right";
					_headTurnDirection = true;
					stage.removeEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
					
					
				}
			}
		}
		

		
			
	}
	
}
